<?php
namespace app\index\model;
use app\common\model\WebOrder as WebOrderModel;
use think\Db;

/**
 * 站点订单模型
 */
class WebOrder extends WebOrderModel
{
    /**
     * 新增订单
     */
    public function add($store_user_id,$pay)
    {
        // 记录订单信息
        return $this->save([
			'order_no' => orderNo(),
			'order_type' => 10,	//充值
			'pay_price' => $pay,
			'pay_status' => 10,	
			'purpose' => '商户充值',
			'affair_id' => $store_user_id,
			
		]);
    }
	/**
     * 续费
     */
    public function upgrade($data)
    {
		write_log($data,__DIR__);
		$edition = WebEdition::detail($data['web_edition_id']);//获取版本详情
		$store = StoreUser::detail($data['store_user_id']);//获取商户详情
		$pay = 0;//支付费用
		//计算费用
		if($data['shop_mode']==10){
			//单商户
			if($store['wallet'] < $edition['buy_single'][$data['year']]){
				$this->error = '账户余额不足，请充值';
				return false;
			}
			$pay = $edition['buy_single'][$data['year']];
		}
		if($data['shop_mode']==20){
			//多商户
			if($store['wallet'] < $edition['buy_many'][$data['year']]){
				$this->error = '账户余额不足，请充值';
				return false;
			}
			$pay = $edition['buy_many'][$data['year']];
		}
		$day = $data['year']*3600*24*365;//计算到期时间
		$app = Wxapp::getWxapp(['wxapp_id' => $data['wxapp_id']]);
		if($pay==0){
			$this->error = '计算错误';
			return false;
		}
		 // 开启事务
        Db::startTrans();
        try {
			//扣除余额
			$store->wallet = ['dec',$pay];
			$store->save();
			//增加到期时间
			$app->expire_time = ['inc',$day];
			$app->save();
            $this->save([
				'order_no' => orderNo(),
				'order_type' => 20,	//扣费
				'pay_price' => $pay,
				'pay_status' => 20,	
				'pay_time' => time(),	
				'purpose' => '小程序续费',
				'affair_id' => $data['wxapp_id'],
				
			]);
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
        }
        return false;
    }
}
